using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;

namespace CriticalSystems.Instrumentation
{
    internal sealed class SystemInformation
    {
        private const string DefaultSystemInstanceName = "Default";
        private const string InstrumentationXmlNamespace =
            "http://criticalsystems.co.uk/schemas/instrumentation/02/2009";
        private string instance;

        public SystemInformation(IXPathNavigable xml)
        {
            var navigator = xml.CreateNavigator();
            navigator.MoveToFirstChild();
            System = navigator.GetAttribute("name", string.Empty);
            Instance = DefaultSystemInstanceName;
            EventLog = navigator.GetAttribute("eventLog", string.Empty);
            DisplayName = navigator.GetAttribute("displayName", string.Empty);
            Version = navigator.GetAttribute("version", string.Empty);
            var nsmgr = new XmlNamespaceManager(navigator.NameTable);
            nsmgr.AddNamespace("i", InstrumentationXmlNamespace);
            var iterator = navigator.Select("i:subsystems/i:subsystem", nsmgr);
            Subsystems = new List<SubsystemInformation>();
            foreach (XPathNavigator nodeIterator in iterator)
            {
                var subsystem = new SubsystemInformation(nodeIterator);
                Subsystems.Add(subsystem);
            }
        }

        public string Version { get; private set; }

        public string DisplayName { get; private set; }

        public string EventLog { get; private set; }

        public string Instance
        {
            get { return instance; }
            set
            {
                if (string.IsNullOrEmpty(value))
                {
                    instance = DefaultSystemInstanceName;
                }
                else {instance = value;}
            }
        }

        public string System { get; private set; }

        public SubsystemInformation this[string subsystem]
        {
            get
            {
                SubsystemInformation si = null;
                foreach (SubsystemInformation s in Subsystems)
                {
                    if (s.Subsystem.ToLowerInvariant().Trim() == subsystem.ToLowerInvariant().Trim())
                    {
                        si = s;
                        break;
                    }
                }
                return si;
            }
        }

        public IList<SubsystemInformation> Subsystems { get; private set; }
    }
}